package com.zp.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.exception.ServiceException;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.core.utils.TreeBuildUtils;
import com.zp.common.satoken.utils.LoginHelper;
import com.zp.system.api.entity.SysDept;
import com.zp.system.api.entity.SysRole;
import com.zp.system.api.entity.SysUser;
import com.zp.system.mapper.SysDeptMapper;
import com.zp.system.mapper.SysRoleMapper;
import com.zp.system.mapper.SysUserMapper;
import com.zp.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 科室管理 服务实现
 *
 * @author zheng peng
 */
@RequiredArgsConstructor
@Service
public class SysDeptServiceImpl implements ISysDeptService {

    private final SysDeptMapper baseMapper;
    private final SysRoleMapper roleMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询科室管理数据
     *
     * @param dept 科室信息
     * @return 科室信息集合
     */
    @Override
    public List<SysDept> selectDeptList (SysDept dept) {
//        LoginUser loginUser =  LoginHelper.getLoginUser();
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDept::getDelFlag, "0")
                .eq(StringUtils.isNotBlank(dept.getOrgId()), SysDept::getOrgId, dept.getOrgId())
                .in(CollectionUtil.isNotEmpty(dept.getClinicVsVisitArray()), SysDept::getClinicOrVisit, dept.getClinicVsVisitArray())
                .eq(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId())
                .eq(ObjectUtil.isNotNull(dept.getParentId()), SysDept::getParentId, dept.getParentId())
                .like(StringUtils.isNotBlank(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName())
                .eq(StringUtils.isNotBlank(dept.getStatus()), SysDept::getStatus, dept.getStatus())
                .orderByAsc(SysDept::getParentId)
                .orderByAsc(SysDept::getOrderNum);
        return baseMapper.selectDeptList(lqw);
    }

    /**
     * 查询科室树结构信息
     *
     * @param dept 科室信息
     * @return 科室树信息集合
     */
    @Override
    public List<Tree<String>> selectDeptTreeList (SysDept dept) {
        List<SysDept> depts = this.selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 科室列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<String>> buildDeptTreeSelect (List<SysDept> depts) {
        if (CollUtil.isEmpty(depts)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(depts, (dept, tree) ->
                tree.setId(dept.getDeptId())
                        .setParentId(dept.getParentId())
                        .setName(dept.getDeptName())
                        .setWeight(dept.getOrderNum()));
    }

    /**
     * 根据角色ID查询科室树信息
     *
     * @param roleId 角色ID
     * @return 选中科室列表
     */
    @Override
    public List<String> selectDeptListByRoleId (String roleId) {
        SysRole role = roleMapper.selectById(roleId);
        return baseMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }

    /**
     * 根据科室ID查询信息
     *
     * @param deptId 科室ID
     * @return 科室信息
     */
    @Override
    public SysDept selectDeptById (String deptId) {
        SysDept dept = baseMapper.selectById(deptId);
        SysDept parentDept = baseMapper.selectOne(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptName).eq(SysDept::getDeptId, dept.getParentId()));
        dept.setParentName(ObjectUtil.isNotNull(parentDept) ? parentDept.getDeptName() : null);
        return dept;
    }

    /**
     * 根据ID查询所有子科室（正常状态）
     *
     * @param deptId 科室ID
     * @return 子科室数
     */
    @Override
    public long selectNormalChildrenDeptById (String deptId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getStatus, UserConstants.DEPT_NORMAL)
                .apply("find_in_set({0}, ancestors) <> 0", deptId));
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 科室ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId (String deptId) {
        return baseMapper.exists(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getParentId, deptId));
    }

    /**
     * 查询科室是否存在用户
     *
     * @param deptId 科室ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser (String deptId) {
        return userMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getDeptId, deptId));
    }

    /**
     * 校验科室名称是否唯一
     *
     * @param dept 科室信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique (SysDept dept) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptName, dept.getDeptName())
                .eq(SysDept::getOrgId, dept.getOrgId())
                .ne(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()));
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验科室代码是否唯一
     *
     * @param dept 科室信息
     * @return 结果
     */
    @Override
    public String checkDeptCodeUnique (SysDept dept) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptCode, dept.getDeptCode())
                .eq(SysDept::getOrgId, dept.getOrgId())
                .ne(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()));
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验科室是否有数据权限
     *
     * @param deptId 科室id
     */
    @Override
    public void checkDeptDataScope (String deptId) {
        if (!LoginHelper.isAdmin()) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = this.selectDeptList(dept);
            if (CollUtil.isEmpty(depts)) {
                throw new ServiceException("没有权限访问科室数据！");
            }
        }
    }

    /**
     * 新增保存科室信息
     *
     * @param dept 科室信息
     * @return 结果
     */
    @Override
    public int insertDept (SysDept dept) {
        SysDept info = baseMapper.selectById(dept.getParentId());
        String ancestors = "";
        if (ObjectUtil.isNotNull(info)) {
            ancestors = info.getAncestors();
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("科室停用，不允许新增");
            }
        }
        dept.setAncestors(ancestors + "," + dept.getParentId());
        return baseMapper.insert(dept);
    }

    /**
     * 修改保存科室信息
     *
     * @param dept 科室信息
     * @return 结果
     */
    @Override
    public int updateDept (SysDept dept) {
        SysDept newParentDept = baseMapper.selectById(dept.getParentId());
        SysDept oldDept = baseMapper.selectById(dept.getDeptId());
        if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = baseMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals(UserConstants.DEPT_NORMAL, dept.getAncestors())) {
            // 如果该科室是启用状态，则启用该科室的所有上级科室
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该科室的父级科室状态
     *
     * @param dept 当前科室
     */
    private void updateParentDeptStatusNormal (SysDept dept) {
        String ancestors = dept.getAncestors();
        String[] deptIds = Convert.toStrArray(ancestors);
        baseMapper.update(null, new LambdaUpdateWrapper<SysDept>()
                .set(SysDept::getStatus, UserConstants.DEPT_NORMAL)
                .in(SysDept::getDeptId, Arrays.asList(deptIds)));
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的科室ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren (String deptId, String newAncestors, String oldAncestors) {
        List<SysDept> childrenBo = baseMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .apply("find_in_set({0},ancestors) <> 0", deptId));
        List<SysDept> list = new ArrayList<>();
        for (SysDept child : childrenBo) {
            SysDept dept = new SysDept();
            dept.setDeptId(child.getDeptId());
            dept.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(dept);
        }
        if (list.size() > 0) {
            baseMapper.updateBatchById(list);
        }
    }

    /**
     * 删除科室管理信息
     *
     * @param deptId 科室ID
     * @return 结果
     */
    @Override
    public int deleteDeptById (String deptId) {
        return baseMapper.deleteById(deptId);
    }

    /**
     * 获取用户权限科室
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysDept> getPersonnelAuthorityDepartment (String userId) {
        List<SysDept> depts = baseMapper.getPersonnelAuthorityDepartment(userId);
        return buildNatureTree(depts);
    }

    public List<SysDept> buildNatureTree (List<SysDept> natureTrees) {
        if (CollectionUtil.isNotEmpty(natureTrees)) {
            List<SysDept> deptList = baseMapper.selectList(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, "0").eq(SysDept::getOrgId, natureTrees.get(0).getOrgId()));
            // 初步处理好的数据
            List<SysDept> returnList = new ArrayList<SysDept>();
            // 所有树 treeId 的 List 集合
            List<String> tempList = new ArrayList<String>();
            for (SysDept natureTree : natureTrees) {
                tempList.add(natureTree.getDeptId());
            }
            // 遍历所有树节点（一个树节点就是数据库中的一条数据）
            for (SysDept natureTree : natureTrees) {
                // 如果是顶级节点, 遍历该父节点的所有子节点
                if (deptList.stream().filter(item -> item.getDeptId().equals(natureTree.getParentId())).findAny().isPresent()) {
                    // 递归处理数据，此处传入的 natureTree 是最顶级节点，没有父节点
                    recursionFn(natureTrees, natureTree);
                    returnList.add(natureTree);
                }
            }
            if (returnList.isEmpty()) {
                returnList = natureTrees;
            }
            return returnList;
        }
        return new ArrayList<>();
    }

    /**
     * 递归列表
     */
    private void recursionFn (List<SysDept> list, SysDept t) {
        // 获取此节点的子节点列表
        List<SysDept> childList = getChildList(list, t);
        // 将子节点 List set 进去
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysDept> it = childList.iterator();
                while (it.hasNext()) {
                    SysDept n = (SysDept) it.next();
                    // 递归
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 获取子节点列表
     */
    private List<SysDept> getChildList (List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotBlank(n.getParentId()) && n.getParentId().equals(t.getDeptId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild (List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 根据科室id获取科室信息
     *
     * @param deptId
     * @return
     */
    @Override
    public SysDept getSysDeptInfo (String deptId) {
        return baseMapper.selectById(deptId);
    }

    ;
}
